package com.yanx.system.web.infra.listener;

import com.yanx.common.command.executor.QueryExecutor;
import com.yanx.system.base.domain.event.SysDictDeleteEvent;
import com.yanx.system.base.domain.event.SysDictSaveEvent;
import com.yanx.system.base.model.vo.SysDictDataVo;
import com.yanx.system.web.infra.cache.SysDictCache;
import com.yanx.system.web.query.SysDictDataListByTypeQry;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.List;

/**
 * 监听数据字典，更新缓存
 *
 * @author gotanks
 * @date 2023/06/07
 */
@Slf4j
@Component
public class SysDictListener {

    @Autowired
    private QueryExecutor queryExecutor;

    @Async
    @TransactionalEventListener
    public void onSysDictSave(SysDictSaveEvent event) {
        String dictType = event.getDictType();
        log.info("更新数据字典缓存->{}->{}", dictType);
        List<SysDictDataVo> sysDictDataVos = queryExecutor.execute(new SysDictDataListByTypeQry(dictType));
        SysDictCache.INSTANCE.set(new String[]{dictType}, sysDictDataVos);
    }

    @Async
    @TransactionalEventListener
    public void onSysDictDelete(SysDictDeleteEvent event) {
        String dictType = event.getDictType();
        log.info("删除数据字典缓存->{}", dictType);
        SysDictCache.INSTANCE.delete(dictType);
    }
}
